/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.web.service.mobile;

import com.imenu.WebApp;
import com.imenu.ejb.ImenuCourseFacade;
import com.imenu.ejb.ImenuFavoriteFacade;
import com.imenu.ejb.ImenuMenuFacade;
import com.imenu.ejb.ImenuOrderFacade;
import com.imenu.ejb.ImenuStoreFacade;
import com.imenu.entity.ImenuCourse;
import com.imenu.entity.ImenuFavorite;
import com.imenu.entity.ImenuMenu;
import com.imenu.entity.ImenuOrder;
import com.imenu.entity.ImenuOrderItem;
import com.imenu.entity.ImenuTag;
import com.imenu.entity.OrderStatus;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Yunzi
 */
@WebServlet(name = "MobileServlet", urlPatterns = {"/mobile"})
public class MobileServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String command = request.getParameter("command");
            if ("menuList".equals(command)) {
                this.menuList(request, response);
            } else if ("orderList".equals(command)) {
                this.orderList(request, response);
            } else if ("cancelOrder".equals(command)) {
                this.cancelOrder(request, response);
            } else if ("doubleCourse".equals(command)) {
                this.doubleCourse(request, response);
            } else if ("deleteCourse".equals(command)) {
                this.deleteCourse(request, response);
            } else if ("courseList1".equals(command)) {
                this.courseList(request, response);
            } else if ("courseList2".equals(command)) {
                this.courseList(request, response);
            } else if ("courseList3".equals(command)) {
                this.courseList(request, response);
            } else if ("courseList4".equals(command)) {
                this.courseList(request, response);
            } else if ("profile".equals(command)) {
                this.profile(request, response);
            }
        } finally {
            out.close();
        }
    }
    
    
    private void profile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        forward(request, response, "/profile/profile.jsp");
    }
    @EJB
    ImenuOrderFacade orderFacade;
    @EJB
    ImenuCourseFacade courseFacade;

    private void doubleCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("MobileServlet.doubleCourse request.getParameter(\"orderId\")=" + request.getParameter("orderId"));
        Integer orderId = Integer.valueOf(request.getParameter("orderId"));
        Integer courseId = Integer.valueOf(request.getParameter("courseId"));
        System.out.println("MobileServlet.doubleCourse orderId=" + orderId + " courseId=" + courseId);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        try {
            ImenuCourse course = courseFacade.find(courseId);
            ImenuOrder order = orderFacade.find(orderId);
            ImenuOrderItem orderItem = new ImenuOrderItem();
            orderItem.setCourseId(course.getId());
            orderItem.setCourseName(course.getName());
            orderItem.setCoursePrice(course.getPrice());
            orderItem.setOrderId(order);
            orderItem.setCreateTime(new java.util.Date());
            order.getOrderItemsCollection().add(orderItem);
            order.setAmount(order.getAmount() + course.getPrice());
            order.getOrderItemsCollection().add(orderItem);
            orderFacade.edit(order);
            //forward(request, response, "/jsp/orderList.jsp");
            //orderList(request, response);
            out.print("{\"success\":true}");
        } catch (Exception e) {
            out.print("{\"success\":false}");
            e.printStackTrace();
        }
    }

    
    private void deleteCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("MobileServlet.deleteCourse request.getParameter(\"orderId\")=" + request.getParameter("orderId"));
        Integer orderId = Integer.valueOf(request.getParameter("orderId"));
        Integer courseId = Integer.valueOf(request.getParameter("courseId"));
        System.out.println("MobileServlet.doubleCourse orderId=" + orderId + " courseId=" + courseId);
        //orderFacade.remove(orderFacade.find(id));
        //forward(request, response, "/jsp/orderList.jsp");
        //orderList(request, response);
        
    }
    

    private void cancelOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("request.getParameter(\"orderId\")=" + request.getParameter("orderId"));
        Integer id = Integer.valueOf(request.getParameter("orderId"));
        orderFacade.remove(orderFacade.find(id));
        //forward(request, response, "/jsp/orderList.jsp");
        orderList(request, response);
    }
    @EJB
    ImenuStoreFacade storeFacade;
    private void orderList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<ImenuOrder> newList = orderFacade.findAll();
        List<ImenuOrder> acceptedList = new ArrayList<ImenuOrder>();
        List<ImenuOrder> doneList = new ArrayList<ImenuOrder>();
        Iterator<ImenuOrder> it = newList.iterator();
        while (it.hasNext()) {
            ImenuOrder order = it.next();

            if (OrderStatus.DONE.getValue().equals(order.getStatus())) {
                doneList.add(order);
                it.remove();
            } else if (OrderStatus.ACCEPTED.getValue().equals(order.getStatus())) {
                acceptedList.add(order);
                it.remove();
            }
        }
        //补充storeName属性，用于页面展示
        for(ImenuOrder order : newList){
            order.setStoreName(storeFacade.find(order.getStoreId()).getStoreName());
        }
        //request.setAttribute("doneList", doneList);
        request.setAttribute("newList", newList);
        request.setAttribute("newListSize", newList.size());
        //request.setAttribute("acceptedList", acceptedList);
        forward(request, response, "/jsp/orderList.jsp");
    }
    private void courseList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("MobileServlet.courseList() request.getParameter(menuName)="+request.getParameter("menuName"));
        System.out.println("MobileServlet.courseList() request.getParameter(menuId)="+request.getParameter("menuId"));
        Integer menuId = Integer.valueOf(request.getParameter("menuId"));
        ImenuMenu menu = menuFacade.find(menuId);
        TreeMap<ImenuTag, List<ImenuCourse>> courseByTag = new TreeMap<ImenuTag, List<ImenuCourse>>();
        for(ImenuCourse course : menu.getImenuCourseCollection()){
            ImenuTag tag = course.getTag();
            if(courseByTag.get(tag) == null){
                courseByTag.put(tag, new ArrayList<ImenuCourse>());
            }
            courseByTag.get(tag).add(course);
        }
        List<ImenuTag> tags = new ArrayList<ImenuTag>();
        List<List<ImenuCourse>> coursesLists = new ArrayList<List<ImenuCourse>>();
        for(ImenuTag tag : courseByTag.keySet()){
            tags.add(tag);
            coursesLists.add(courseByTag.get(tag));
        }
        String tagIdParam = request.getParameter("tagId");
        ImenuTag preTag = null;
        ImenuTag curTag = null;
        ImenuTag nexTag = null;
        
        if(tagIdParam == null){
            if(tags.size()>0) curTag = tags.get(0);
            if(tags.size()>1) nexTag = tags.get(1);
        }else{
            try{
                Integer tagId = Integer.valueOf(tagIdParam);
                for(int i=0; i<tags.size(); i++){
                    if(tags.get(i).getId().equals(tagId)){
                        //System.out.println("bingo i="+i+" tags.size() = "+tags.size());
                        curTag = tags.get(i);
                        if(i>0) preTag = tags.get(i-1);
                        if((tags.size() - i)>1) nexTag = tags.get(i+1);
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        List<ImenuCourse> courses = courseByTag.get(curTag);
        //System.out.println("tagId="+tagIdParam);
        //System.out.println("preTag="+preTag);
        //System.out.println("curTag="+curTag);
        //System.out.println("nexTag="+nexTag);
        
        request.setAttribute("menuId", menuId);
        request.setAttribute("preTag", preTag);
        request.setAttribute("curTag", curTag);
        request.setAttribute("nexTag", nexTag);
        request.setAttribute("courses", courses);
        forward(request, response, "/jsp/"+request.getParameter("command")+".jsp");
    }
    @EJB
    ImenuMenuFacade menuFacade;

    @EJB ImenuFavoriteFacade favoriteFacade;
    private void menuList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("MobileServlet.courseList() request.getQueryString()="+request.getQueryString());
        System.out.println("MobileServlet.courseList() request.getParameter(deviceId)="+request.getParameter("deviceId"));
        System.out.println("MobileServlet.courseList() request.getParameter(command)="+request.getParameter("command"));
        List<ImenuMenu> menuList = menuFacade.findAll();
        Map<Integer, ImenuFavorite> favoriteMap = new HashMap<Integer, ImenuFavorite>();
        Collection<ImenuFavorite> favoriteMenus = favoriteFacade.findFavoritesByDeviceId(request.getParameter("deviceId"));
        for(ImenuFavorite f : favoriteMenus){
            favoriteMap.put(f.getMenuId(), f);
        }
        List<ImenuFavorite> favoriteList = new ArrayList<ImenuFavorite>();
        Iterator<ImenuMenu> it = menuList.iterator();
        while (favoriteMenus.size() > 0 && it.hasNext()) {
            ImenuMenu menu = it.next();
            if (favoriteMap.containsKey(menu.getId())) {
                favoriteList.add(favoriteMap.get(menu.getId()));
                favoriteMap.get(menu.getId()).setMenu(menu);
                it.remove();
            }
        }
        System.out.println("MobileServlet.courseList() favoriteList = "+favoriteList);
        request.setAttribute("favoriteList", favoriteList);
        request.setAttribute("restList", menuList);
        forward(request, response, "/jsp/menuList.jsp");
    }
    
    private void forward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        String path = url;
        System.out.println("MobileServlet.forward() path = " + path);
        getServletContext().getRequestDispatcher(path).forward(request, response);
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    @Inject
    WebApp webApp;

    public void init() {
        System.out.println("MobileServlet.init() ........................");
        webApp.setRoot(getServletContext().getContextPath());
        getServletContext().setAttribute("webApp", webApp);
        System.out.println("MobileServlet.init() ........................ webApp.root = " + webApp.getRoot());
    }
}
